#include "loginManage.h"
#include "ui_loginManage.h"
#include "register.h"

LoginManage::LoginManage(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginManage)
{
    ui->setupUi(this);
    setWindowTitle(tr("用户管理"));//窗口标题
    user = new LoginUser();

    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    //根据内容自动调整列宽
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    //最后一行是否铺满剩余空间
    ui->tableView->horizontalHeader()->setStretchLastSection(true);

    //隔行变色
    ui->tableView->setAlternatingRowColors(true);
}

LoginManage::~LoginManage()
{
    if(user){
        user->deleteLater();
    }
    delete ui;
}

void LoginManage::on_pushButton_add_user_clicked()
{
    user->clear();
    Register *reg = new Register();
    reg->setParent(this);
    reg->setTiteName("新增用户信息");
    reg->exec();

    if(user->getIsUpdate()){
        dlogin->getLoginDB()->addUser(user);
        ui->tableView->setFocus();
    }
}

void LoginManage::on_pushButton_del_user_clicked()
{
    int row = ui->tableView->currentIndex().row();
    dlogin->getLoginDB()->deleteUser(row);
    ui->tableView->setFocus();
}

void LoginManage::on_pushButton_cancel_clicked()
{
    this->close();
}

LoginUser *LoginManage::getUser() const
{
    return user;
}

void LoginManage::setParent(Dialog_Login *login)
{
    if(login)
    {
        dlogin = login;
        if(dlogin->getLoginDB()->getModel()){
            ui->tableView->setModel(dlogin->getLoginDB()->getModel());
        }
    }
}

void LoginManage::on_pushButton_update_clicked()
{
    int row = ui->tableView->currentIndex().row();
    dlogin->getLoginDB()->getUserById(user,row);

    Register *reg = new Register();
    reg->setParent(this);
    reg->setTiteName("修改用户信息");
    reg->setUserInfo();
    reg->exec();

    if(user->getIsUpdate()){
        dlogin->getLoginDB()->updateUser(user,row);
        ui->tableView->setFocus();
    }
}
